package com.cai.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class Tests2 {
    @Autowired
    RedisTemplate<String,Integer> redisTemplate;
    private static final DatagramSocket  socket;
    static {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    private static final String ADDRESS="localhost";
    private static final Integer PORT=9999;
    private String returnMsg = null;
    public String client2(String message) {
        try {
            redisTemplate.opsForHash().put("port","client2",socket.getLocalPort());
            // 准备要发送的数据
            byte[] sendData = message.getBytes();
            InetAddress serverInetAddress = InetAddress.getByName(ADDRESS);
            // 创建数据包用于发送数据
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverInetAddress, PORT);
            // 发送数据包到服务器
            socket.send(sendPacket);
            // 创建数据包用于接收服务器的响应
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            // 接收服务器的响应
            socket.receive(receivePacket);
            // 提取响应数据
            returnMsg= new String(receivePacket.getData(), 0, receivePacket.getLength());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMsg;
    }
}
